package Lucene;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/** Simple command-line based search demo. */
public class SearchEngine 
{
  public SearchEngine() {}

  /** Simple command-line based search demo. */
  public ArrayList<String> ACT001_getSearchResult(String searchWord, String dirPath_index) throws Exception 
  {
	  //System.out.println("-------------------Show search result :" + searchWord + "-------------------");
	  ArrayList<String> list_result = new ArrayList<String>();
      String field = "contents";
      //do query according to the index file
      IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(dirPath_index)));
      IndexSearcher searcher = new IndexSearcher(reader);
      Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
      QueryParser parser = new QueryParser(Version.LUCENE_40, field, analyzer);
      Query query = parser.parse(searchWord);
      //get query result
      TopDocs results = searcher.search(query, 70000000);
	  ScoreDoc[] hits = results.scoreDocs;
	  int numTotalHits = results.totalHits;
	  int indexResult = 0;
	  //System.out.println(numTotalHits + " total matching documents");
	  while(indexResult < numTotalHits)
	  {
		  Document doc = searcher.doc(hits[indexResult].doc);
	      String path = doc.get("path");
	      list_result.add(path);
		  indexResult = indexResult + 1;
	  }
	  reader.close();
      return list_result;
  }
  public void ACT002_showSearchResult(ArrayList<String> list)
  {
	  int index = 0;
	  while(index < list.size())
	  {
		  System.out.println(list.get(index));
		  index = index + 1;
	  }
  }
  public static void main(String[] args) throws Exception 
  {
	  SearchEngine SE = new SearchEngine();
	  ArrayList<String> list = SE.ACT001_getSearchResult("i", "/root/Desktop/index");
	  SE.ACT002_showSearchResult(list);
  }
}
